package models

import (
	"fmt"

	"github.com/astaxie/beego/orm"
)

type Ban struct {
	Id         int
	Code       string //命令
	CreateTime int64  //创建时间
	UpdateTime int64  //更新时间
	Status     int    //状态  0-正常  1-删除
}

func (ban *Ban) TableName() string {
	return TableName("task_ban")
}

func (ban *Ban) Update(fields ...string) error {
	if ban.Code == "" {
		return fmt.Errorf("命令不能为空")
	}
	if _, err := orm.NewOrm().Update(ban, fields...); err != nil {
		return err
	}
	return nil
}

func BanGetList(page, pagesize int, filters ...interface{}) ([]*Ban, int64) {

	query := orm.NewOrm().QueryTable(TableName("task_ban"))

	//判断过滤条件
	if len(filters) > 0 {
		//获取过滤条件的长度
		j := len(filters)

		//遍历过滤条件
		for k := 0; k < j; k += 2 {
			query = query.Filter(filters[k].(string), filters[k+1])
		}

	}

	totle, _ := query.Count()

	list := make([]*Ban, 0)

	//计算偏移量
	offset := (page - 1) * pagesize

	//分页查找
	query.OrderBy("-id").Limit(pagesize, offset).All(&list)

	return list, totle
}

//
func BanGetById(id int) (*Ban, error) {
	ban := new(Ban)
	err := orm.NewOrm().QueryTable(TableName("task_ban")).Filter("id", id).One(ban)

	if err != nil {
		return nil, err
	}
	return ban, nil
}

func BanAdd(ban *Ban) (int64, error) {
	return orm.NewOrm().Insert(ban)
}
